﻿using MySqlConnector;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DAL
{
    public class AttendanceService
    {
        public Attendance GetAttendance(string memberid, int activityid)
        {
            string sql = "select * from attendance where memberid=@memberid and activityid=@activityid";
            MySqlParameter[] para = new MySqlParameter[2];
            para[0] = new MySqlParameter("@memberid", memberid);
            para[1] = new MySqlParameter("@activityid", activityid);
            DataTable dt;
            try
            {
                dt = SQLHelper.ExecuteQuery(sql, para);
            }
            catch (Exception ex) { throw new Exception(ex.Message); }
            Attendance attendance = null;
            if (dt.Rows.Count != 0)
            {
                int id = Convert.ToInt32(dt.Rows[0]["id"]);
                string mid = dt.Rows[0]["memberid"].ToString();
                int actid = Convert.ToInt32(dt.Rows[0]["activityid"].ToString());
                bool attend = Convert.ToBoolean(dt.Rows[0]["attend"]);
                attendance = new Attendance(id, actid, mid, attend);

            }
            return attendance;
        }
        public bool AddAttendance(Attendance attendance)
        {
            string sql = "insert into attendance values(@id,@activityid,@memberid,@attend)";
            MySqlParameter[] para = new MySqlParameter[4];
            para[0] = new MySqlParameter("@id", attendance.Id);
            para[1] = new MySqlParameter("@memberid", attendance.Memberid);
            para[2] = new MySqlParameter("@activityid", attendance.Activityid);
            para[3] = new MySqlParameter("@attend", attendance.Attend);
            try
            {
                int n = SQLHelper.ExecuteNonQuery(sql.ToString(), para);
                if (n > 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex) { throw new Exception(ex.Message); }
        }
        public bool UpdateAttendance(Attendance attendance)
        {
            string sql = "update attendance set attend=@attend where id =@id";
            MySqlParameter[] para = new MySqlParameter[2];
            para[0] = new MySqlParameter("@id", attendance.Id);
            para[1] = new MySqlParameter("@attend", attendance.Attend);
            try
            {
                int n = SQLHelper.ExecuteNonQuery(sql.ToString(), para);
                if (n > 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex) { throw new Exception(ex.Message); }
        }
    }
}
